<?php

namespace App\Http\Controllers\Users;
use App\Blocks\User;
use App\Http\Controllers\Controller;
use EasyWeChat\Factory;
use Illuminate\Http\Request;

class UserController extends Controller {

    public function weixinCallback(Request $request){
        $app = Factory::officialAccount(\Config::get('wechat'));
        $oauth = $app->oauth;
        $user = $oauth->user();

        $userBlock = new User();
        $userInfo = $userBlock->getUserByWxOpenid($user->getId());
        if(!$userInfo){
            $wxuser = $user->toArray();
            $wxuser = $wxuser['original'];

            global $wechatId;

            $saveUserData = [
                'wechat_id'         => $wechatId,
                'subscribe_time'    => date('Y-m-d H:i:s', isset($wxuser['subscribe_time'])?$wxuser['subscribe_time']:time()),
                'openid'            => $wxuser['openid'],
                'nickname'          => $wxuser['nickname'],
                'city'              => $wxuser['city'],
                'province'          => $wxuser['province'],
                'country'           => $wxuser['country'],
                'sex'               => $wxuser['sex'],
                'headimgurl'        => $wxuser['headimgurl'],
                'subscribe'         => isset($wxuser['subscribe'])?$wxuser['subscribe']:0,
                'create_time'       => date('Y-m-d H:i:s', time())
            ];
            $userId = $userBlock->saveUserByWeixin($saveUserData);

            if($userId){
                $userInfo = [
                    'openid' => $saveUserData['openid'],
                    'headimgurl' => $saveUserData['headimgurl'],
                    'nick_name' => $saveUserData['nickname'],
                    'mobile' => null,
                    'id' => $userId
                ];
                $userInfo = (object)$userInfo;
            }
        }

        if(isset($userInfo->id)){
            if(isset($userInfo->create_time)){
                unset($userInfo->create_time);
            }
            $sessionKey = md5($userInfo->openid);
            \Cache::put($sessionKey, $userInfo, \Config::get('session.lifetime'));
            $cookie = \Cookie::make(\Config::get('session.user_cookie'), $sessionKey, \Config::get('session.lifetime'));

            $userInfo->token = $sessionKey;

            if($request->has('redirect')){
                if($request->get('redirect') == 'index'){
                    return redirect(env('WEB_URL').'/mastedu/enroll?appid='.$request->get('appid').'&token='.$sessionKey)->withCookie($cookie);
                }else{
                    return redirect(env('WEB_URL').'/mastedu/enroll?appid='.$request->get('appid').'&token='.$sessionKey)->withCookie($cookie);
                }
            }
            return response()->json($userInfo)->withCookie($cookie);
        }else{
            return response()->json(['error' => '登录失败']);
        }
    }

    public function testLogin(){
        return response()->json(['test' => 'test']);
    }
}